<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>商品介紹</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item label="商品ID" prop="id">
          <el-input v-model="goods.id" disabled />
        </el-form-item>
        <el-form-item label="商品名稱" prop="name">
          <el-input v-model="goods.name" />
        </el-form-item>
        <el-form-item label="商品貨號" prop="artNo">
          <el-input v-model="goods.artNo" />
        </el-form-item>
        <!--<el-form-item label="商品副標題" prop="subheading">
          <el-input v-model="goods.subheading" />
        </el-form-item>-->
        <!-- <el-form-item label="商品編號" prop="goodsSn">
          <el-input v-model="goods.goodsSn" />
        </el-form-item>-->
        <!-- <el-form-item label="市場售價" prop="counterPrice">
          <el-input v-model="goods.counterPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item> -->
        <el-form-item label="商品重量" prop="weight">
          <el-input v-model="goods.weight" placeholder="0" maxlength="11" show-word-limit  onkeyup="value=value.replace(/[^\d]/g,'')">
            <template slot="append">克</template>
          </el-input>
        </el-form-item>
        <el-form-item label="pv值" prop="pvValue">
          <el-input v-model="goods.pvValue" placeholder="0" maxlength="11" show-word-limit onkeyup="value=value.replace(/[^\d]/g,'')">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="是否推薦" prop="isNew">
          <el-radio-group v-model="goods.isNew">
            <el-radio :label="false">非推薦</el-radio>
            <el-radio :label="true">推薦</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="是否套餐" prop="isSetMeal">
          <el-radio-group v-model="goods.isSetMeal" @change="gotaocan">
            <el-radio :label="false">非套餐</el-radio>
            <el-radio :label="true">套餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否冷凍商品" prop="isFrozen">
          <el-radio-group v-model="goods.isFrozen">
            <el-radio :label="false">非冷凍</el-radio>
            <el-radio :label="true">冷凍</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" prop="isOnSale">
          <el-radio-group v-model="goods.isOnSale">
            <el-radio :label="true">上架</el-radio>
            <el-radio :label="false">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品圖片">
          <el-upload
            :headers="headers"
            action="http://www.hometasty.info/demo/up.php"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif"
          >
            <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="宣傳畫廊">
          <el-upload
             action="http://www.hometasty.info/demo/up.php"
            :headers="headers"
            :limit="5"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>

        <el-form-item label="商品單位">
          <el-input v-model="goods.unit" placeholder="件 / 個 / 盒" />
        </el-form-item>

        <!-- <el-form-item label="關鍵字">
          <el-tag v-for="tag in keywords" :key="tag" closable type="primary" @close="handleClose(tag)">
            {{ tag }}
          </el-tag>
          <el-input v-if="newKeywordVisible" ref="newKeywordInput" v-model="newKeyword" class="input-new-keyword" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else class="button-new-keyword" type="primary" @click="showInput">+ 增加</el-button>
        </el-form-item>-->

        <el-form-item label="所屬分類">
          <el-cascader
            v-model="categoryIds"
            :options="categoryList"
            :props="{ checkStrictly: true }"
            clearable
            expand-trigger="hover"
            @change="handleCategoryChange"
          />
        </el-form-item>

        <!-- <el-form-item label="所屬品牌商">
          <el-select v-model="goods.brandId" clearable>
            <el-option v-for="item in brandList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>-->

        <el-form-item label="商品說明">
          <editor v-model="goods.brief" :init="editorInit" />
        </el-form-item>

        <el-form-item label="商品描述">
          <editor v-model="goods.detail" :init="editorInit" />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <el-card class="box-card">
      <h3>商品規格</h3>
      <el-table :data="specifications">
        <el-table-column property="specification" label="規格名" />
        <el-table-column property="value" label="規格值">
          <template slot-scope="scope">
            <el-tag type="primary">{{ scope.row.value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="picUrl" label="規格圖片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleSpecificationShow(scope.row)">設置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="specVisiable" title="設置規格">
        <el-form
          ref="specForm"
          :rules="rules"
          :model="specForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="規格名" prop="specification">
            <el-input v-model="specForm.specification" disabled />
          </el-form-item>
          <el-form-item label="規格值" prop="value">
            <el-input v-model="specForm.value" disabled />
          </el-form-item>
          <el-form-item label="規格圖片" prop="picUrl">
            <el-upload
              :headers="headers"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="uploadSpecPicUrl"
              class="avatar-uploader"
              accept=".jpg, .jpeg, .png, .gif"
            >
              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleSpecificationEdit">確定</el-button>
        </div>
      </el-dialog>
    </el-card> -->

    <el-card class="box-card">
      <h3>商品庫存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="貨品規格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">{{ tag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" label="貨品售價" />
        <el-table-column property="number" label="貨品數量" />
        <el-table-column property="counterPrice"  label="折扣售價" />
        <el-table-column property="url" label="貨品圖片">
          <template slot-scope="scope">
            <img v-if="scope.row.url" :src="scope.row.url" width="40" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">設置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="productVisiable" title="編輯貨品">
        <el-form
          ref="productForm"
          :model="productForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="貨品規格列" prop="specifications">
            <el-tag v-for="tag in productForm.specifications" :key="tag">{{ tag }}</el-tag>
          </el-form-item>
          <el-form-item label="貨品售價" prop="price">
            <el-input v-model="productForm.price" type="number"/>
          </el-form-item>
          <el-form-item label="折扣售價" prop="counterPrice">
            <el-input v-model="productForm.counterPrice" type="number"/>
          </el-form-item>
          <el-form-item label="貨品數量" prop="number">
            <el-input v-model="productForm.number" maxlength="11" show-word-limit  onkeyup="value=value.replace(/[^\d]/g,'')"/>
          </el-form-item>
          <el-form-item label="貨品圖片" prop="url">
            <el-upload
              :headers="headers"
               action="http://www.hometasty.info/demo/up.php"
              :show-file-list="false"
              :on-success="uploadProductUrl"
              class="avatar-uploader"
              accept=".jpg, .jpeg, .png, .gif"
            >
              <img v-if="productForm.url" :src="productForm.url" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleProductEdit">確定</el-button>
        </div>
      </el-dialog>
    </el-card>
    <el-card class="box-card" v-if="goods.isSetMeal == 1">
      <el-row>
        <el-col :span="22">
          <h3>套餐商品</h3>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" size="mini" @click="selectgoods()">选择商品</el-button>
        </el-col>
      </el-row>


      <el-table :data="goodsItem">
        <el-table-column  label="商品名称">
          <template slot-scope="scope">
            {{scope.row.name}}
          </template>
        </el-table-column>
        <el-table-column width="100" label="貨品售價">
          <template slot-scope="scope">
            价格：&{{scope.row.counterPrice}}
          </template>
          <!--  <div>
              价格：&88
            </div>-->
          <!--          <template slot-scope="scope">-->
          <!--          货品售价：辅导班不VB发的 -->
          <!--          </template>-->
        </el-table-column>
        <el-table-column prop="number" width="100" label="套餐内數量">
          <template slot-scope="scope">
            {{scope.row.num}}
          </template>
        </el-table-column>
        <el-table-column  width="100" label="貨品圖片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width;">
          <template slot-scope="scope">
            <el-row style="display:flex;align-items:center">
              <el-col>
                <el-button type="primary" size="mini" @click="changegoods(scope.row)">编辑</el-button>
              </el-col>
              <el-button type="text"  @click="deletetaocan(scope.row.id)">删除</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
<!--      商品-->
      <el-dialog :visible.sync="selectVisiable" title="选择商品">
        <el-form
          ref="selectForm"
          :model="selectForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="选择商品" prop="value">
            <el-select v-model="selectForm.value" >
              <el-option v-for="item in selectOption" :key="item.goodsId" :value="item.goodsId" :label="item.goodsName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="selectForm.number" type="number" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectVisiable = false">取消</el-button>
          <el-button type="primary" @click="selectgoodsSure">確定</el-button>
        </div>
      </el-dialog>
<!--      //编辑-->
      <el-dialog :visible.sync="selectVisiable1" title="编辑">
        <el-form
          ref="selectForm1"
          :model="selectForm1"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
<!--          <el-form-item label="选择商品" prop="value">-->
<!--            <el-select v-model="selectForm.value" >-->
<!--              <el-option v-for="item in selectOption" :key="item.goodsId" :value="item.goodsId" :label="item.goodsName">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->

          <el-form-item label="数量" prop="num">
            <el-input v-model="selectForm1.num" type="number" />
          </el-form-item>
          <el-input v-model="selectForm1.id" type="hidden" />
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectVisiable1 = false">取消</el-button>
          <el-button type="primary" @click="selectgoodsSure1">確定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新商品</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.op-container {
  display: flex;
  justify-content: center;
}
</style>

<script>
import { detailGoods, editGoods, listCatAndBrand, deleteGoodsItem, selectGoods, addGoodsItem,updateGoodsItem } from '@/api/goods'
import { createStorage, uploadPath } from "@/api/storage";
import Editor from "@tinymce/tinymce-vue";
import { MessageBox } from "element-ui";
import { getToken } from "@/utils/auth";

export default {
  name: "GoodsEdit",
  components: { Editor },
  data() {
    return {
      taocan:false,
      uploadPath,
      newKeywordVisible: false,
      newKeyword: "",
      keywords: [],
      galleryFileList: [],
      categoryList: [],
      brandList: [],
      categoryIds: [],
      goods: { gallery: [] },
      specVisiable: false,
      selectVisiable:false,
      selectVisiable1:false,
      specForm: { specification: "", value: "", picUrl: "" },
      specifications: [{ specification: "規格", value: "標準", picUrl: "" }],
      goodsItem:[],
      selectOption:[],
      selectOption1:[],
      productVisiable: false,
      selectForm:{
        value:"请选择商品",
        number:0
      },
      selectForm1:{
        id:0,
        num:0
      },
      productForm: {
        id: 0,
        specifications: [],
        price: 0.0,
        number: 0,
        url: "",
        counterPrice: 0.0
    },
      products: [
        { id: 0, specifications: ["標準"], price: 0.0, number: 0, url: " ", counterPrice: 0.0 },
      ],
      attributeVisiable: false,
      attributeAdd: true,
      attributeForm: { attribute: "", value: "" },
      attributes: [],
      rules: {
        name: [
          { required: true, message: "商品名稱不能為空", trigger: "blur" },
        ],
      },
      editorInit: {
        language: "zh_CN",
        height: "400px",
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount",
        ],
        toolbar: [
          "fontsizeselect searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen",
        ],
        images_upload_handler: function (blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then((res) => {
              
              success(res.data.url);
            })
            .catch(() => {
              failure("上傳失敗，請重新上傳");
            });
        },
      },
    };
  },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
    attributesData() {
      var attributesData = [];
      for (var i = 0; i < this.attributes.length; i++) {
        if (this.attributes[i].deleted) {
          continue;
        }
        attributesData.push(this.attributes[i]);
      }
      return attributesData;
    },
  },
  created() {
    this.init();
  },
  methods: {
    gotaocan() {
      // if(this.goods.isSetMeal){
      //   this.goods.isSetMeal = 1
      // }else{
      //   this.goods.isSetMeal = 0
      // }
    },
    changegoods(row){
      // changegoods().then(response => {
      //   if (response.data.errno == 0) {
      //     this.selectOption1 = response.data.data
      //   } else {
      //     this.selectOption1 = []
      //   }
      // })
      // // console.log(this.selectgoods)
      this.selectForm1 = row
      this.selectVisiable1 = true
      // // this.selectOption
    },
    selectgoods(){
      selectGoods().then(response => {
        if (response.data.errno == 0) {
          this.selectOption = response.data.data
        } else {
          this.selectOption = []
        }
      })
      // console.log(this.selectgoods)
      this.selectVisiable = true
      // this.selectOption
    },
    selectgoodsSure(){
      var item
      for (var i = 0;i<this.selectOption.length;i++){
        if(this.selectOption[i].goodsId == this.selectForm.value){
          item = this.selectOption[i]
          // item.name = this.selectOption[i].goodsName
          // item.goodsId = this.selectOption[i].goodsId
          // item.goodsSn = this.selectOption[i].goodsSn
          // item.counterPrice = this.selectOption[i].retailPrice
          console.log(item)
          // return
        }
      }
      item.number = this.selectForm.number
      item.num = this.selectForm.number
      item.setmeal = this.$route.query.id;

      console.log(item)
      //this.goodsItem.push(item)
      addGoodsItem(item).then(response => {
        if(response.data.errno != 0){
          MessageBox.alert('業務錯誤：' + response.data.errmsg, '警告', {
            confirmButtonText: '確定',
            type: 'error'
          })
          return false;
        }
        this.$notify.success({
          title: '成功',
          message: '創建成功'
        })
       // this.$store.dispatch('tagsView/delView', this.$route)
        //this.$router.push({ path: '/goods/list' })
      }).catch(response => {
        MessageBox.alert('業務錯誤：' + response.data.errmsg, '警告', {
          confirmButtonText: '確定',
          type: 'error'
        })
      })
      this.init()
      this.selectVisiable = false
    },
    selectgoodsSure1(){
      console.log(this.selectForm1)
      var id = this.selectForm1.id
      var num = this.selectForm1.num
      updateGoodsItem(id,num).then(response => {
        if(response.data.errno != 0){
          MessageBox.alert('業務錯誤：' + response.data.errmsg, '警告', {
            confirmButtonText: '確定',
            type: 'error'
          })
          return false;
        }
        this.$notify.success({
          title: '成功',
          message: '創建成功'
        })
        // this.$store.dispatch('tagsView/delView', this.$route)
        //this.$router.push({ path: '/goods/list' })
      }).catch(response => {
        MessageBox.alert('業務錯誤：' + response.data.errmsg, '警告', {
          confirmButtonText: '確定',
          type: 'error'
        })
      })
      this.init()
      this.selectVisiable1 = false
    },
    init: function () {
      if (this.$route.query.id == null) {
        return;
      }


      const goodsId = this.$route.query.id;
      detailGoods(goodsId).then((response) => {
        this.goods = response.data.data.goods;
        // 稍微調整壹下前後端不壹致
        if (this.goods.brandId === 0) {
          this.goods.brandId = null;
        }
        if (this.goods.keywords === "") {
          this.goods.keywords = null;
        }

          this.specifications = response.data.data.specifications;
          this.products = response.data.data.products;
          this.attributes = response.data.data.attributes;
          this.categoryIds = response.data.data.categoryIds;
          this.goodsItem = response.data.data.litemallGoodsItems;
        this.galleryFileList = [];
        for (var i = 0; i < this.goods.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.goods.gallery[i],
          });
        }
        const keywords = response.data.data.goods.keywords;
        if (keywords !== null) {
          this.keywords = keywords.split(",");
        }
      });

      listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      });
    },
    handleCategoryChange(value) {
      this.goods.categoryId = value[value.length - 1];
    },
    handleCancel: function () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/goods/list" });
    },
    handleEdit: function () {
      const finalGoods = {
        goods: this.goods,
        specifications: this.specifications,
        products: this.products,
        attributes: this.attributes,
      };
      editGoods(finalGoods)
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "編輯成功",
          });
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push({ path: "/goods/list" });
        })
        .catch((response) => {
          MessageBox.alert("業務錯誤：" + response.data.errmsg, "警告", {
            confirmButtonText: "確定",
            type: "error",
          });
        });
    },
    deletetaocan(id){
      deleteGoodsItem(id)
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "删除成功",
          });
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push({ path: "/goods/list" });
        })
        .catch((response) => {
          MessageBox.alert("業務錯誤：" + response.data.errmsg, "警告", {
            confirmButtonText: "確定",
            type: "error",
          });
        });
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.goods.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick((_) => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.goods.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    },
    uploadPicUrl: function (response) {
      this.goods.picUrl = response.url;
    },
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: "上傳文件個數超出限制!最多上傳5張圖片!",
      });
    },
    handleGalleryUrl(response, file, fileList) {
      // if (response.errno === 0) {
        this.goods.gallery.push(response.url);
      // }
    },
    handleRemove: function (file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 這裏存在兩種情況
        // 1. 如果所刪除圖片是剛剛上傳的圖片，那麽圖片地址是file.response.data.url
        //    此時的file.url雖然存在，但是是本機地址，而不是遠程地址。
        // 2. 如果所刪除圖片是後臺返回的已有圖片，那麽圖片地址是file.url
        var url;
        if (file.response === undefined) {
          url = file.url;
        } else {
          url = file.response.data.url;
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1);
        }
      }
    },
    specChanged: function (label) {
      if (label === false) {
        this.specifications = [
          { specification: "規格", value: "標準", picUrl: "" },
        ];
        this.products = [
          { id: 0, specifications: ["標準"], price: 0.0, number: 0, url: "",counterPrice: 0.0 },
        ];
      } else {
        this.specifications = [];
        this.products = [];
      }
    },
    uploadSpecPicUrl: function (response) {
      this.specForm.picUrl = response.url;
    },
    handleSpecificationShow(row) {
      this.specForm = Object.assign({}, row);
      this.specVisiable = true;
    },
    handleSpecificationEdit() {
      this.specForm.updateTime = "";
      for (var i = 0; i < this.specifications.length; i++) {
        const v = this.specifications[i];
        if (v.id === this.specForm.id) {
          this.specifications.splice(i, 1, this.specForm);
          break;
        }
      }
      this.specVisiable = false;
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row);
      this.productVisiable = true;
    },
    uploadProductUrl: function (response) {
      this.productForm.url = response.url;
    },
    handleProductEdit() {
      this.productForm.updateTime = "";
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i];
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm);
          break;
        }
      }
      this.productVisiable = false;
    },
    handleAttributeShow(row) {
      if (row.id) {
        this.attributeForm = Object.assign({}, row);
        this.attributeAdd = false;
      } else {
        this.attributeForm = {};
        this.attributeAdd = true;
      }
      this.attributeVisiable = true;
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm);
      this.attributeVisiable = false;
    },
    handleAttributeEdit() {
      // 這是壹個trick，設置updateTime的值為空，告訴後端這個記錄已編輯需要更新。
      this.attributeForm.updateTime = "";
      for (var i = 0; i < this.attributes.length; i++) {
        const v = this.attributes[i];
        if (v.id === this.attributeForm.id) {
          this.attributes.splice(i, 1, this.attributeForm);
          break;
        }
      }
      this.attributeVisiable = false;
    },
    handleAttributeDelete(row) {
      row.deleted = true;
    },
  },
};
</script>
